import { Injectable } from '@nestjs/common';
import { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
import { isEmpty } from 'lodash';
import { EntityManager, Repository, TreeRepository, Like } from 'typeorm';
import { paginate } from '~/helper/paginate';
import { Pagination } from '~/helper/paginate/pagination';

import { BusinessException } from '~/common/exceptions/biz.exception';
import { ErrorEnum } from '~/constants/error-code.constant';
import { PostEntity } from '~/modules/system/post/post.entity';

import { PostDto, PostQueryDto } from './post.dto';

@Injectable()
export class PostService {
  constructor(
    @InjectRepository(PostEntity)
    private postRepository: TreeRepository<PostEntity>
  ) {}

  async list({
    name,
    page,
    pageSize,
  }: PostQueryDto): Promise<Pagination<PostEntity>> {
    const queryBuilder = this.postRepository.createQueryBuilder('post').where({
      ...(name ? { name: Like(`%${name}%`) } : null),
    });

    return paginate<PostEntity>(queryBuilder, {
      page,
      pageSize,
    });
  }

  async info(id: number): Promise<PostEntity> {
    const post = await this.postRepository
      .createQueryBuilder('post')
      .where({ id })
      .getOne();

    if (isEmpty(post)) throw new BusinessException(ErrorEnum.POST_NOT_FOUND);

    return post;
  }

  async create(data: PostDto): Promise<void> {
    //先判断name和code有没有重复的
    const exist = await this.postRepository.findOne({
      where: [{ name: data.name }, { code: data.code }],
    });
    if (exist && exist.name === data.name)
      throw new BusinessException(ErrorEnum.POST_IS_EXIST);
    if (exist && exist.code === data.code)
      throw new BusinessException(ErrorEnum.POSTCODE_IS_EXIST);

    await this.postRepository.save({
      ...data,
    });
  }

  async update(id: number, data: PostDto): Promise<void> {
    //先判断name和code有没有重复的，并且id不等于当前id

    const exist = await this.postRepository.findOne({
      where: [{ name: data.name }, { code: data.code }],
    });
    console.log(11111, exist);
    if (exist && exist.id !== id && exist.name === data.name)
      throw new BusinessException(ErrorEnum.POST_IS_EXIST);

    if (exist && exist.id !== id && exist.code === data.code)
      throw new BusinessException(ErrorEnum.POSTCODE_IS_EXIST);

    const item = await this.postRepository
      .createQueryBuilder('post')
      .where({ id })
      .getOne();
    await this.postRepository.save({
      ...item,
      ...data,
    });
  }

  async delete(id: number): Promise<void> {
    await this.postRepository.delete(id);
  }

  /**
   * 根据岗位ID查找是否有关联用户
   */
  async checkUserByPostId(id: number): Promise<boolean> {
    return this.postRepository.exists({
      where: {
        users: {
          posts: { id },
        },
      },
    });
  }
}
